<template>
  <component
    :is="isModal ? AModal : ADrawer"
    v-model:visible="innerVisible"
    :class="[innerVisible && !isModal ? 'w-auto md:!w-168 p-3' : 'py-3']"
    :title="isModal ? '新增点位' : '编辑点位'"
    :get-container="isModal ? 'body' : drawerContainerSelector"
    :style="isModal ? { width: '720px' } : { padding: 0 }"
    :mask="isModal"
    :body-style="{ paddingBottom: 0 }"
    :content-wrapper-style="{ position: 'static', borderRadius: '4px', overflow: 'hidden' }"
    closable
  >
    <DynamicForm
      ref="equipmentAttrIns"
      :force-column="true"
      :model="model"
      :model-form-setting="modelFormSetting"
      @init="equipmentAttrInit"
    />
    <DataTypeForm
      ref="dataTypeIns"
      v-model:valueDataType="model.dataType"
      v-model:equipment-attr-model="equipmentAttrModel"
    />
    <template #footer>
      <div class="flex flex-row items-center justify-between">
        <div v-if="!isModal" class="flex-1">
          <a-button v-show="!hideNextPrev" type="text" :disabled="preDisabled" @click="updateNextOrPrev(-1)">
            <Icon type="icon-zuo" class="!align-middle h-4" />
            <span class="align-middle">上一个</span>
          </a-button>
          <a-button v-show="!hideNextPrev" type="text" :disabled="nextDisabled" @click="updateNextOrPrev(1)">
            <span class="align-middle">下一个</span>
            <Icon type="icon-you" class="!align-middle h-4" />
          </a-button>
        </div>
        <div v-else></div>
        <div class="flex flex-row items-center">
          <a-button @click="innerVisible = false">取消</a-button>
          <a-button :type="isModal ? undefined : 'primary'" class="ml-2" @click="ok(false)">确定</a-button>
          <a-button v-show="isModal" class="ml-2" type="primary" @click="ok(true)">确定并继续新增</a-button>
        </div>
      </div>
    </template>
  </component>
</template>
<script setup lang="ts">
import { Modal as AModal, Drawer as ADrawer, message } from "ant-design-vue";
import { onMounted, ref, watch, computed, nextTick } from "vue";
import { DynamicFormExpose, FormItemComponentType, FormItemData } from "/@/components/CURDDialog/models";
import { EquipmentAttrItem, GroupOptions, ParEquipmentAttrItem } from "/@/api/aiot/equipmentType/models";
import { getDictionaryByType } from "/@/api/aiot/dictionary";
import { attrAdd, attrAddSys, attrUpdate, attrUpdateSys, equipmentGroupPage } from "/@/api/aiot/equipmentType";
import { PatternKey } from "/@/utils/verify";
import { stringify } from "querystring";
import { extend } from "lodash";

const props = withDefaults(
  defineProps<{
    visible: boolean;
    drawerContainerSelector?: string;
    equipmentAttr?: ParEquipmentAttrItem;
    isEnterprise: boolean;
    options: GroupOptions;
    hideNextPrev?: boolean;
    preDisabled?: boolean;
    nextDisabled?: boolean;
  }>(),
  {
    drawerContainerSelector: "#home-content",
    preDisabled: false,
    nextDisabled: false,
    hideNextPrev: false,
  }
);
const isModal = computed(() => {
  return props.equipmentAttr?.equipmentTypeAttributeId || props.equipmentAttr?.defaultEquipmentTypeAttributeId
    ? false
    : true;
});
const emits = defineEmits(["update:visible", "done", "update:equipmentAttr", "handlePreOrNext"]);
const innerVisible = ref(props.visible);
const dataTypeIns = ref();
const equipmentAttrModel = ref<ParEquipmentAttrItem>({});
const model = ref<ParEquipmentAttrItem>({
  attributeName: "",
  attributeDisplayName: "",
  equipmentParamGroupsId: "",
  attributeLevel: "import",
  display: "true",
  readWriteType: "R",
  dataType: "int",
  defaultEquipmentTypeAttributeId: "",
  equipmentTypeAttributeId: "",
});
// property
// service
// event
var modelFormSetting: FormItemData[] = [
  {
    key: "attributeName",
    label: "点位名称 ",
    required: true,
    max: 32,
  },
  {
    key: "attributeDisplayName",
    label: "参数名称(显示名称)",
    labelDes: "若不填写，系统自动默认为点位名称",
    max: 32,
  },
  {
    key: "equipmentParamGroupsId",
    label: "参数分组 ",
    required: true,
    type: FormItemComponentType.TREESELECT,
    async getData() {
      // equipmentGroupPage equipmentGroupPageSys
      let data = await equipmentGroupPage(props.options.equipmentTypeId);
      console.info("data==>", data);
      return data?.records || [];
    },
    props: {
      fieldNames: { label: "equipmentParamGroupsName", value: "equipmentParamGroupsId" },
    },
  },
  {
    key: "attributeLevel",
    label: "功能级别 ",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "重要", value: "import" },
        { label: "次要", value: "minor" },
        { label: "一般", value: "general" },
      ],
    },
  },
  {
    key: "display",
    label: "是否显示 ",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "显示", value: "true" },
        { label: "不显示", value: "false" },
      ],
    },
  },
  {
    key: "readWriteType",
    label: "读写类型 ",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "只读", value: "R" },
        { label: "读写", value: "RW" },
      ],
    },
  },
  //   string
  // float
  // int
  // boolean
  {
    key: "dataType",
    label: "数据类型 ",
    type: FormItemComponentType.SELECT,
    required: true,
    async getData() {
      let data = await getDictionaryByType({ dictionaryType: "DATATYPE" });
      return data
        ? data.map((el) => ({
            label: el.dictionaryName,
            value: el.dictionaryCode,
          }))
        : [];
    },
    props: {
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "equipmentTypeAttributeId",
    hide: true,
  },
  {
    key: "defaultEquipmentTypeAttributeId",
    hide: true,
  },
];
// watch(
//   () => model.value.functionType,
//   (v) => {
//     nextTick(() => {
//       v === "event" ? (model.value.dataType = "boolean") : (model.value.dataType = "");
//       // equipmentAttrIns.value && equipmentAttrIns.value?.toggleField("eventType", v !== "event");
//       // equipmentAttrIns.value && equipmentAttrIns.value?.setFieldRquired("eventType", v === "event");
//     });
//   },
//   {
//     deep: true,
//     immediate: true,
//   }
// );
watch(innerVisible, (v) => {
  emits("update:visible", v);
});
let firstShow = true;
watch(
  () => props.visible,
  (v) => {
    innerVisible.value = v;
    if (v) {
      if (equipmentAttrIns.value) {
        equipmentAttrIns.value?.reloadFormItemComponentData("equipmentParamGroupsId");
      }
      if (firstShow) {
        firstShow = false;
      }
    } else {
      reset();
    }
  }
);
watch(
  () => props.equipmentAttr,
  (val) => {
    equipmentAttrModel.value = JSON.parse(JSON.stringify(props.equipmentAttr)) || {};
    if (props.equipmentAttr) {
      for (let key in model.value) {
        if (key === "display") {
          model.value[key] = props.equipmentAttr.display + "";
        } else {
          model.value[key] = props.equipmentAttr[key];
        }
      }
    }
    if (JSON.stringify(props.equipmentAttr) === "{}") {
      // model.value.functionType = "property";
      model.value.readWriteType = "R";
      model.value.attributeLevel = "import";
      model.value.display = "true";
      model.value.dataType = "int";
      model.value.equipmentParamGroupsId = props.options.equipmentParamGroupsId || "";
    }
  }
);
function reset() {
  equipmentAttrIns.value?.resetFields();
  dataTypeIns.value?.rest();
  emits("update:equipmentAttr", {});
}
/**
 * base info
 */
const equipmentAttrIns = ref<DynamicFormExpose>();

function equipmentAttrInit() {
  if (equipmentAttrIns.value) {
    equipmentAttrIns.value.initFormItemComponentData();
  }
}

async function ok(isContinue) {
  // attrAdd
  equipmentAttrIns.value?.validate().then(async () => {
    let obj = Object.assign({}, model.value);
    // 合并 不同数据类型对应的值
    obj = Object.assign(obj, dataTypeIns.value.formData);
    // 设备类型id
    obj.equipmentTypeId = props.options.equipmentTypeId;
    // 设备功能分组code
    // obj.groupCode = props.options.groupCode;
    // 设置功能分组ID 新需求改为自选分组
    // obj.equipmentParamGroupsId = props.options.equipmentParamGroupsId;
    // 功能属性为不事件时候 清空事件类型字段数据 功能类型是事件 事件类型默认 = alarm
    // model.value.functionType !== "event" ? (model.value.eventType = "") : (model.value.eventType = "alarm");
    // return;
    // 如果参数名称（显示名称）没有输入，默认等于点位名称

    // display 字符串改为boolean
    // 判断model.value.dataType = "boolean" 如果是boolean 布尔值为必填
    if (obj.dataType === "boolean") {
      let extendObj = JSON.parse(obj.extend);
      if (!extendObj || !extendObj.falseDesc || !extendObj.trueDesc) {
        message.warning("请输入布尔值");
        return;
      }
    }
    obj.display = obj.display === "true";
    model.value.attributeDisplayName ? null : (obj.attributeDisplayName = model.value.attributeName);
    let req = false;
    if (props.equipmentAttr?.equipmentTypeAttributeId || props.equipmentAttr?.defaultEquipmentTypeAttributeId) {
      if (props.isEnterprise) {
        req = (await attrUpdate(obj)) || false;
      } else {
        req = (await attrUpdateSys(obj)) || false;
      }
    } else {
      if (props.isEnterprise) {
        req = (await attrAdd(obj)) || false;
      } else {
        req = (await attrAddSys(obj)) || false;
      }
    }
    if (req) {
      message.success("操作成功");
      if (isContinue) {
        reset();
      } else {
        innerVisible.value = false;
      }
      emits("done");
    }
  });
}
function updateNextOrPrev(d: number) {
  emits("handlePreOrNext", d);
}
</script>
